package com.csw.shuanfa.other;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author 1
 */
@Slf4j
public class HttpTestAction {
    private static final String SUCCESS = "success";
    private static final String TRUE = "true";

    /**
     * 这里是本人进行的调试，作为记录使用，仅供参考
     */
    public static void main(String[] args) throws Exception {

        /* http接口地址 */
        String urlHead = "http:127.0.0.1:8089/bpm/bpmservice";
        /* 流程模板编码 */
        String modelKey = "HR_INTEGRAL_EXCHANGEPLAN_APPLY";
        String applyId = initApplyId();
        /* 流程申请编码 */
        /* String applyId = "QJ-20190312105823001"; */
        /* 流程发起人编码 */
        String loginId = "admin";
        /* 流程接收人编码 */
        String staffCode = "10001";
        /* URLEncoder.encode()方法 为字符串进行编码 */
        String userName = URLEncoder.encode("管理员", "UTF-8");
        /*
         * 1：新建流程
         */
        JSONObject result1 = load(
                urlHead + "/process/startProcessByModelKey?loginId=" + loginId + "&modelKey=" + modelKey,
                "{applyId:'" + applyId + "',userName:'" + userName + "',staffCode:'" + staffCode + "'}");
        boolean boolean1 = false;
        if (result1 != null) {
            if (Objects.equals(result1.getString(SUCCESS), TRUE)) {
                boolean1 = true;
            }
        }
        if (boolean1) {
            /* 2：根据流程实例获取待办任务id */
            JSONObject result2 = load(urlHead + "/worktask/getUserTaskByPId?loginId=" + staffCode
                    + "&processInstanceId=" + result1.get("processInstanceId"), "");

            boolean boolean2 = false;
            if (result2 != null) {
                if (Objects.equals(result2.getString(SUCCESS), TRUE)) {
                    boolean2 = true;
                }
            }
            if (boolean2) {
                /* 3：根据流程id获取流程信息 */
                JSONObject result3 = load(
                        urlHead + "/worktask/getTaskDealInfo?loginId=" + staffCode + "&taskId=" + result2.get("taskId"),
                        "");
                String array = null;

                if (result3 != null) {
                    array = result3.getString("taskDealInfo");
                }
                JSONObject result4 = JSONObject.parseObject(array);

                if (Objects.equals(result4.getString(SUCCESS), TRUE)) {
                    /* 4：拼接待办页面url */
                    String formUrl = result4.get("formUrl") + "?applyId=" + applyId + "&flowInstId="
                            + result1.get("processInstanceId") + "&taskId=" + result2.get("taskId");
                }
            }
        }
    }

    public static JSONObject load(String url, String data) {
        String encoding = "UTF-8";
        HttpURLConnection httpConnection = null;
        PrintWriter printWriter = null;
        StringBuilder stringBuilder = new StringBuilder();
        /* 用来存储响应数据 */
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        JSONObject resultJson = null;
        try {

            URL targetUrl = new URL(url);
            /* 新建链接实例 */
            httpConnection = (HttpURLConnection) targetUrl.openConnection();
            /* 设置链接超时时间，单位毫秒 */
            httpConnection.setConnectTimeout(2000);
            /* 设置读取数据超时时间，单位毫秒 */
            httpConnection.setReadTimeout(2000);
            /* 是否打开输出流true|false */
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            /* 设置提交方法 POST|GET */
            httpConnection.setRequestMethod("POST");
            /* 是否使用缓存true|false */
            httpConnection.setUseCaches(false);
            httpConnection.setRequestProperty("Accept-Charset", encoding);
            /* 标准的HTTP POST是一种application/x-www-form-urlencoded 类型的网络表单，传递的参数都会被写入请求信息主体中 */
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding);
            httpConnection.setRequestProperty("Content-Type", "application/json");

            /* 建立连接 (请求未开始,直到connection.getInputStream() */
            /* 方法调用时才发起,以上各个参数设置需在此方法之前进行) */
            httpConnection.connect();

            /* 获取URLConnection对象对应的输出流 */
            printWriter = new PrintWriter(httpConnection.getOutputStream());
            /* 发送请求参数即数据 */
            printWriter.print(data);
            /* 输出完成后刷新并关闭流 */
            printWriter.flush();
            printWriter.close();

            /* 这里返回200,则是成功调用接口，否则失败 */
            int successStateCode = 200;
            if (httpConnection.getResponseCode() == successStateCode) {
                /* 得到响应流 */
                inputStream = httpConnection.getInputStream();
                /* 处理服务器响应 (将从连接获取到输入流包装为bufferedReader) */
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
                String line;
                /* 循环读取流,若不到结尾处 */
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                /* 关闭流 */
                bufferedReader.close();
                inputStream.close();
            } else {
                stringBuilder.append("{\"success\":\"false\",\"message\":\"调用http接口失败！\"}");
            }

            /* 关闭连接 */
            httpConnection.disconnect();
            /* 转换成json对象 */
            resultJson = JSONObject.parseObject(stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        }

        return resultJson;
    }

    public static String initApplyId() {
        /* 获取当前时间当做任务编码的sql */

        return null;

    }

}
